// pages/me/group-manage/group-manage.js
const https = require('../../../utils/https.js')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    inputId: 0,
    form: {
      id: 0,
      name: ''
    },
    inputValue: '',
    dataList: [],
    dialogShow: false,
    buttons: [{text: '取消'}, {text: '确定'}],
  },
  back() {
    wx.navigateBack({
      delta: 1
    })
  },
  changeInput(e) {
    this.data.inputValue = e.detail.value
    console.log(this.data.inputValue)
  },
  switchInput(e) {
    if (e.currentTarget.dataset.id == 0) {
      this.data.form = {
        id: e.currentTarget.dataset.item.id,
        name: this.data.inputValue
      }
      console.log(this.data.inputValue)
      console.log(this.data.form)
      this.addData()
      this.setData({
        inputId: 0
      })
    } else {
      this.setData({
        inputId: e.currentTarget.dataset.id,
        inputValue: e.currentTarget.dataset.item.name
      })
    }
  },
  getData() {
    https.get('/api/group', {}).then((res) => {
      if (res.code == 0) {
        this.setData({
          dataList: res.data.data
        })
      }
    })
  },
  addData(e) {
    if (this.data.form.name == '') return
    https.post('/api/group/update', this.data.form).then((res) => {
      if (res.code == 0) {
        this.setData({
          'form.name': '',
          'form.id': 0
        })
        this.getData()
      }
      if (res.msg) {
        wx.showToast({
          title: res.msg,
          icon: 'none', // error loading none
          mask: true, // 是否显示透明蒙层，防止触摸穿透
          duration: 1000
        })
      }
    })
  },
  setDelId(e) {
    this.data.del_id = e.currentTarget.dataset.id
    this.setData({
      dialogShow: true
    })
  },
  delData(id) {
    id = id ? id : this.data.del_id
    https.post('/api/group/destroy', { id }).then((res) => {
      if (res.code == 0) {
        this.getData()
        res.msg = '删除成功'
      }
      if (res.msg) {
        wx.showToast({
          title: res.msg,
          icon: 'none', // error loading none
          mask: true, // 是否显示透明蒙层，防止触摸穿透
          duration: 1000
        })
      }
    })
  },
  tapDialogButton(e) {
    this.setData({
      dialogShow: false
    })
    if (e.detail.index == 1) {
      // 确定
      this.delData()
    } else {
      // 取消
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getData()
  }
})